<template>
	<view class="my-bluetooth-index" style="box-sizing: border-box; width: 700rpx;height: 60px;
				 margin: 0 auto; display: flex;
				 align-items: center;">
		<view class="open" @click="openBluetoothAdapter"
			  style="box-sizing: border-box; width: 100px;height: 40px;">
			<view 
				style="box-sizing: border-box; width: 100px;height: 40px;background-color: white;
					   border: 2px solid black;box-shadow: 3px 3px 0 0 black;
					   font-weight: bold;text-align: center;line-height: 40px;">
			搜索蓝牙</view>
		</view>
		<view class="open" @click="stopBluetoothDevicesDiscovery"
			  style="box-sizing: border-box; width: 750rpx;">
			<view 
				style="box-sizing: border-box; width: 100px;height: 40px;background-color: white;
					   border: 2px solid black;box-shadow: 3px 3px 0 0 black;
					   font-weight: bold;text-align: center;line-height: 40px;margin-left: 20px;">
			停止搜索</view>
		</view>
		<view class="open" @click="writeBLECharacteristicValue"
			  style="box-sizing: border-box; width: 750rpx;">
			<view 
				style="box-sizing: border-box; width: 100px;height: 40px;background-color: white;
					   border: 2px solid black;box-shadow: 3px 3px 0 0 black;
					   font-weight: bold;text-align: center;line-height: 40px;margin-left: 20px;">
			向目标写内容</view>
		</view>
	</view>
	<view class="connect_message" 
		  style="box-sizing: border-box;padding: 0 10px 10px 10px; 
				 width: 700rpx;margin: 10px auto;border-radius: 5px;
				 line-height: 30px;box-shadow: 0 0 10px 0 #ccc;">
		<view>
			当前连接的id: {{connectedDeviceId}}
		</view>
		<view>
			当前连接的服务id: {{serviceId}}
		</view>
		<view>
			读特征: {{readCharacteristic}}
		</view>
		<view>
			写特征: {{writeCharacteristicId}}
		</view>
		<view>
			indicate: {{indicateCharacteristicId}}
		</view>
		<view>
			notify: {{notifyCharacteristicId}}
		</view>
		<view @click="closeBluetoothDevice(connectedDeviceId)"
			style="box-sizing: border-box; width: 80px;height: 30px;background-color: white;
				   border: 2px solid black;box-shadow: 3px 3px 0 0 black;
				   font-weight: bold;text-align: center;line-height: 30px;">
		断开连接</view>
	</view>
	<view>
		<view v-for="item in devices" :key="item.deviceId"
			  style="width: 700rpx;margin: 0 auto;background-color: #ccc;
			  			 box-shadow: inset 0 0 10px 0 #aaa;
			  			 border-radius: 10px;box-sizing: border-box;
			  			 padding: 5px;margin-bottom: 10px;">
			<view class="name">
				设备名称: {{item.name}}
			</view>
			<view class="deviceId">
				设备id: {{item.deviceId}}
			</view>
			<view class="rssi">
				设备信号: {{item.RSSI}}
			</view>
			<view class="connectable">
				是否可连接: 
				<text v-if="item.connectable" 
					  style="background-color: lightgreen;border-radius: 5px;">是</text>
				<text v-if="!item.connectable" 
					  style="background-color: orangered;border-radius: 5px;">否</text>
			</view>
			<view class="do_btn"
				  style="box-sizing: border-box; padding: 0 20px;
						 width: 700rpx;height: 50px;display: flex;
						 justify-content: end;align-items: center;">
				<view @click="connectBluetoothDevice(item)"
					style="box-sizing: border-box; width: 100px;height: 40px;background-color: white;
						   border: 2px solid black;box-shadow: 3px 3px 0 0 black;
						   font-weight: bold;text-align: center;line-height: 40px;">
				连接</view>
				<!-- <view @click="closeBluetoothDevice(item.deviceId)"
					style="box-sizing: border-box; width: 100px;height: 40px;background-color: white;
						   border: 2px solid black;box-shadow: 3px 3px 0 0 black;
						   font-weight: bold;text-align: center;line-height: 40px;">
				断开连接</view> -->
			</view>
		</view>
	</view>
	<view class="mp3">
		<audio 
			id="audio"
			controls="true"
			src="https://www.metamirror.cn:8085/profile/upload/2024/06/30/start.mp3">
		</audio>
	</view>
</template>

<script>
export default {
  data() {
    return {
      devices: [], // 存储搜索到的蓝牙设备
      connectedDeviceId: '' ,// 已连接的蓝牙设备ID
	  connectDevice: {}, // 已连接的蓝牙设备
	  serviceId: '', // 服务的id
	  readCharacteristic: '', // 读特征
	  writeCharacteristicId: '', // 写特征
	  indicateCharacteristicId: '',
	  notifyCharacteristicId: '',
    };
  },
  onShow() {
  	console.log("蓝牙页面onShow")
  },
  methods: {
	  open(){
	  	this.$refs.popup.open("right")
	  },
	// 向蓝牙写东西
	writeBLECharacteristicValue() {
		let buffer = this.generateCommand(0xAA, 0x01);
		uni.writeBLECharacteristicValue({
		    deviceId: this.connectedDeviceId,
		    serviceId: this.serviceId,
		    characteristicId: this.writeCharacteristicId,
		    value: buffer,
		    success(res) {
		        console.log('指令下发成功', res);
		    },
		    fail(error) {
		        console.log('指令发送失败', error);
		    }
		});
	},
	// 解析蓝牙的数据
	handleResponse(responseData) {
	    const parsedData = parseBlueResponse(responseData);
	    console.log('解析后的响应数据：', parsedData);
	},
	 
	parseBlueResponse(responseData) {
	    const dataList = responseData.match(/.{1,2}/g);
	    const [resCode, resType, resResult] = dataList.splice(0, 3);
	    return {
	        resCode,
	        resType,
	        resResult,
	        dataList
	    };
	},
	/**
	 * 生成 ArrayBuffer 格式的数据，可以直接用于给蓝牙设备发送数据
	 * @param {Number} startCode 起始码
	 * @param {Number} dataType 数据类型
	 * @param {Array} sentData 发送给蓝牙的数据数组，例如：[0x12,0x01]
	 */
	generateCommand(startCode, dataType, sentData = []) {
	    let buffer = new ArrayBuffer(20);
	    let dataView = new DataView(buffer);
	    dataView.setUint8(0, startCode);
	    dataView.setUint8(1, dataType);
	    sentData.forEach((data, index) => {
	        dataView.setUint8(2 + index, data);
	    });
	    return buffer;
	},
    // 打开蓝牙适配器
    openBluetoothAdapter() {
		uni.openBluetoothAdapter({
			success: (res) => {
			  console.log('蓝牙适配器开启成功', res);
			  this.startBluetoothDevicesDiscovery();
			},
			fail: (err) => {
			  console.log('蓝牙适配器开启失败', err);
			  uni.showToast({
			  	title: '请先打开手机蓝牙',
				icon: 'error'
			  })
			}
		});
	},
    // 搜索蓝牙设备
    startBluetoothDevicesDiscovery() {
		uni.startBluetoothDevicesDiscovery({
			success: (res) => {
			  console.log('搜索设备成功', res);
			  this.onBluetoothDeviceFound();
			},
			fail: (err) => {
			  console.log('搜索设备失败', err);
			}
		});
	},
	// 停止搜索
	stopBluetoothDevicesDiscovery() {
		uni.stopBluetoothDevicesDiscovery({
			success(res) {
				console.log(res)
				uni.showToast({
					title: "已经停止搜索",
					icon: "none"
				})
			},
			fail: (err) => {
				uni.showToast({
					title: "停止搜索失败",
					icon: "none"
				})
				console.log('搜索设备失败', err);
			}
		})
	},
    // 监听寻找到新设备的事件
    onBluetoothDeviceFound() {
		uni.onBluetoothDeviceFound((devices) => {
			console.log('发现新设备', devices);
			this.devices = this.devices.concat(...devices.devices);
			console.log('发现新设备', this.devices);
		});
	},
	// 连接成功后可以获取设备的服务和特征值
	getBLEDeviceServices() {
		uni.getBLEDeviceServices({
		    deviceId: this.connectedDeviceId,
		    success: (res) => {
		        console.log('成功获取蓝牙设备的所有服务', res);
		        this.serviceId = res.services.find(service => service.isPrimary).uuid;  // 获取主要服务
		        this.getBLEDeviceCharacteristics();
		    },
		    fail: (error) => {
		        console.log('获取蓝牙设备的服务失败', error);
		    }
		});
	},
	// 获取蓝牙服务特征
	getBLEDeviceCharacteristics() {
		uni.getBLEDeviceCharacteristics({
		    deviceId: this.connectedDeviceId,
		    serviceId: this.serviceId,
		    success: (res) => {
		        console.log('获取 characteristic 成功', res);
		        const characteristics = res.characteristics;
				var read = characteristics.find(c => c.properties.read);
				if(read) {
					this.readCharacteristic = read.uuid;  // 找到读特征值
				}
		        var write = characteristics.find(c => c.properties.write);
		        if(write) {
		        	this.writeCharacteristicId = write.uuid;  // 找到写特征值
		        }
				var indicate = characteristics.find(c => c.properties.indicate);
				if(indicate) {
					this.indicateCharacteristicId = indicate.uuid;  // 找到indicate特征值
				}
				var notify = characteristics.find(c => c.properties.notify);
				if(notify) {
					this.notifyCharacteristicId = notify.uuid;  // 找到notify特征值
				}
		        this.startNotify();
		    },
		    fail: (error) => {
		        console.log('获取 characteristic 失败', error);
		    }
		});
	},
	// 启动 notify 监听
	startNotify() {
	    uni.notifyBLECharacteristicValueChange({
	        state: true,
	        deviceId: this.connectedDeviceId,
	        serviceId: this.serviceId,
	        characteristicId: this.readCharacteristic,
	        success: (res) => {
	            console.log("开启 notify 功能成功", res);
	            uni.onBLECharacteristicValueChange((res) => {
	                // let resHex = ab2hex(res.value);
	                console.log("接收到回传内容：", resHex);
	                this.handleResponse(resHex);
	            });
	        },
	        fail: (error) => {
	            console.log("监听失败", error);
				uni.onBLECharacteristicValueChange((res) => {
				    // let resHex = ab2hex(res.value);
				    console.log("接收到回传内容：", resHex);
				    this.handleResponse(resHex);
				});
	        }
	    });
	},
    // 连接蓝牙设备
    connectBluetoothDevice(item) {
		if(!item.connectable) {
			uni.showToast({
				title: "当前设备不可连接",
				icon: "error"
			})
			return;
		} else {
			uni.showToast({
				title: "连接中",
				icon: "loading"
			})
		}
		uni.createBLEConnection({
			deviceId: item.deviceId,
				success: (res) => {
				  uni.showToast({
				  	title: "连接成功",
					icon: "none"
				  })
				  console.log('连接设备成功', res);
				  this.connectedDeviceId = item.deviceId;
				  this.connectDevice = item;
				  // 连接成功后的操作，如开启通知、读写数据等
				  // 连接成功后可以获取设备的服务和特征值
				  setTimeout(() => this.getBLEDeviceServices(), 1000); // 延迟1秒获取服务
				},
				fail: (err) => {
					uni.showToast({
						title: "连接失败",
						icon: "none"
					})
				  console.log('连接设备失败', err);
				}
			});
		},
	// 断开连接蓝牙设备
	closeBluetoothDevice(deviceId) {
		if(!this.connectedDeviceId) {
			uni.showToast({
				title: "还未连接设备",
				icon: "error"
			})
			return;
		}
		uni.closeBLEConnection({
			deviceId: deviceId,
			success: (res) => {
			  uni.showToast({
				title: "断开连接成功",
				icon: "none"
			  })
			  this.connectedDeviceId = '';
			  this.connectDevice = {};
			  this.serviceId = '';
			  this.readCharacteristic = '';
			  this.writeCharacteristicId = '';
			  this.indicateCharacteristicId = '';
			  this.notifyCharacteristicId = '';
			},
			fail: (err) => {
				uni.showToast({
					title: "断开连接失败",
					icon: "none"
				})
				console.log("断开连接失败", err)
			}
		});
	}
},
    onUnload() {
		// 页面销毁时，关闭蓝牙适配器
		uni.closeBluetoothAdapter({
		  success: (res) => {
			console.log('蓝牙适配器关闭成功', res);
		  },
		  fail: (err) => {
			console.log('蓝牙适配器关闭失败', err);
		  }
		});
	  }
	};
</script>

<style>

</style>
